package com.du.config;

import java.lang.reflect.Array;

/**
 * @Desc :
 * @Author: shuangdu
 * @date : 2021/3/30
 */
public class MyArray<T> {

    private int defaultLength;
    private int size;
    private Object[] array;

    public MyArray() {
        this.defaultLength = 2 ^ 3;
        this.array = new Object[this.defaultLength];
    }

    public void add(T data) {
        grow(size + 1);
        array[size++] = data;
    }

    public T get(int index) {
        return (T)array[index];
    }

    private int nullLength() {
        int nullLength = 0;
        for (int i = 0;i<this.array.length; i++) {
            if (this.get(i) == null) nullLength ++;
        }
        return nullLength;
    }

    public T[] getArray(Class<T> type) {
        T[] o = (T[]) Array.newInstance(type, this.array.length - nullLength());
        int j = 0;
        for (int i = 0;i<this.array.length; i++) {
            if (this.get(i) != null) {
                o[j] = this.get(i);
                j++;
            }
        }
        return o;
    }

    private void grow(int size) {
        if (array.length < size) {
            int length = array.length << 1;
            Object[] newObj = new Object[length];
            System.arraycopy(array, 0, newObj, 0, array.length);
            this.array = newObj;
        }
    }
}
